//
//  SyncMutableArray.m
//  BaoVn
//
//  Created by Phuong Le on 6/6/13.
//  Copyright (c) 2013 Phuong Le. All rights reserved.
//

#import "SyncMutableArray.h"

@implementation SyncMutableArray

- (id)init
{
    self = [super init];
    
    if (self)
    {
        _mutableArray = [[NSMutableArray alloc] init];
    }
    
    return self;
}

#pragma mark - Property
- (NSUInteger)count
{
    @synchronized(_mutableArray)
    {
        if (_mutableArray == nil)
        {
            return 0;
        }
        
        return [_mutableArray count];
    }
}

#pragma mark - Init

- (id)initWithArray:(NSMutableArray *)array
{
    self = [super init];
    
    if (self)
    {
        _mutableArray = array;
    }
    
    return self;
}

#pragma mark - Object
- (id)objectAtIndex:(NSUInteger)index
{
    if (index == NSNotFound)
    {
        return nil;
    }
    
    @synchronized(_mutableArray)
    {
        if (_mutableArray == nil || [_mutableArray count] <= index)
        {
            return nil;
        }
        
        return [_mutableArray objectAtIndex:index];
    }
}

#pragma mark - Index
- (NSUInteger)indexOfObject:(id)anObject
{
    @synchronized(_mutableArray)
    {
        if (_mutableArray == nil)
        {
            return NSNotFound;
        }
        
        return [_mutableArray indexOfObject:anObject];
    }
}

#pragma mark - Insert
- (void)addObject:(id)anObject
{
    @synchronized(_mutableArray)
    {
        if (_mutableArray == nil)
        {
            return;
        }
        
        [_mutableArray addObject:anObject];
    }
}

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
{
    @synchronized(_mutableArray)
    {
        if (_mutableArray == nil)
        {
            return;
        }
        
        [_mutableArray insertObject:anObject atIndex:index];
    }
}

#pragma mark - Replace
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)object
{
    if (index == NSNotFound)
    {
        return;
    }
    
    @synchronized(_mutableArray)
    {
        if (_mutableArray == nil || [_mutableArray count] <= index)
        {
            return;
        }
        
        [_mutableArray replaceObjectAtIndex:index withObject:object];
    }
}

#pragma mark - Remove
- (void)removeAllObjects
{
    @synchronized(_mutableArray)
    {
        if (_mutableArray == nil)
        {
            return;
        }
        
        [_mutableArray removeAllObjects];
    }
}

- (void)removeObject:(id)anObject
{
    @synchronized(_mutableArray)
    {
        if (_mutableArray == nil)
        {
            return;
        }
        
        [_mutableArray removeObject:anObject];
    }
}

- (void)removeObjectAtIndex:(NSUInteger)index
{
    if (index == NSNotFound)
    {
        return;
    }
    
    @synchronized(_mutableArray)
    {
        if (_mutableArray == nil || [_mutableArray count] <= index)
        {
            return;
        }
        
        [_mutableArray removeObjectAtIndex:index];
    }
}
@end
